package com.alibaba.citrus.ots.application.report.ability.facade.job;

import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.BaselineBatchQueryPlatforms2Request;
import com.epoch.app.bcorder.model.dto.PlatformSDO;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.model.dto.SearchScItemRequest;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.otsapplicationreportsdk.commercustomerplanreport.dto.BatchAddRequest;
import com.epoch.app.otsapplicationreportsdk.commercustomerplanreport.dto.BatchAddResponse;
import com.epoch.app.otsapplicationreportsdk.commercustomerplanreport.dto.DeleteVersionRequest;
import com.epoch.app.otsapplicationreportsdk.commercustomerplanreport.dto.DeleteVersionResponse;
import com.epoch.app.otsapplicationreportsdk.commercustomerplanreport.dto.LoadListForPageResponse;
import com.epoch.app.otsapplicationreportsdk.commercustomerplanreport.model.CommerCustomerPlanReport;
import com.epoch.app.otsapplicationreportsdk.commercustomerplanreport.service.CommerCustomerPlanReportService;
import com.epoch.app.otsapplicationreportsdk.commercustomerplanreporttask.service.CommerCustomerPlanReportTaskService;
import com.epoch.app.otsapplicationreportsdk.contants.OtsApplicationReportSdkConstants;
import com.epoch.app.otsapplicationreportsdk.model.dto.CommerCustomerPlanReportLoadListVO;
import com.epoch.app.otsapplicationreportsdk.oarsbomonthlyplanofcommercereport.dto.GetListOarsBoMonthlyPlanOfCommerceReportRequest;
import com.epoch.app.otsapplicationreportsdk.oarsbomonthlyplanofcommercereport.dto.GetListOarsBoMonthlyPlanOfCommerceReportResponse;
import com.epoch.app.otsapplicationreportsdk.oarsbomonthlyplanofcommercereport.model.OarsBoMonthlyPlanOfCommerceReport;
import com.epoch.app.otsapplicationreportsdk.oarsbomonthlyplanofcommercereport.service.OarsBoMonthlyPlanOfCommerceReportService;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Primary
@Component
public class CommerCustomerPlanReportJob implements CommerCustomerPlanReportTaskService {
    private static Log log = Log.getLogger(CommerCustomerPlanReportJob.class);
    @Resource
    OarsBoMonthlyPlanOfCommerceReportService oarsBoMonthlyPlanOfCommerceReportService;

    @Resource
    CommerCustomerPlanReportService commerCustomerPlanReportService;

    @Resource
    private BaseDataService baseDataService;

    @Override
    public Object commerCustomerPlanReportTaskJob() {

        // 1、查询es全量数据
        List<OarsBoMonthlyPlanOfCommerceReport> allPlan = getAllPlan();
        // 2、插入新版本
        int version = 1;
        LoadListForPageResponse loadListForPageResponse = commerCustomerPlanReportService.loadListForPage(new CommerCustomerPlanReportLoadListVO());
        if (!ObjectUtils.isEmpty(loadListForPageResponse) && !CollectionUtils.isEmpty(loadListForPageResponse.getResult())) {
            CommerCustomerPlanReport commerCustomerPlanReport = loadListForPageResponse.getResult().get(0);
            version += commerCustomerPlanReport.getAddVersion();
        }
        addPlanCommerceReport(allPlan, version);
        // 3、删除就版本全部数据
        if (!ObjectUtils.isEmpty(loadListForPageResponse) && !CollectionUtils.isEmpty(loadListForPageResponse.getResult())) {
            CommerCustomerPlanReport commerCustomerPlanReport = loadListForPageResponse.getResult().get(0);
            DeleteVersionRequest versionRequest = DeleteVersionRequest.builder().addVersion(commerCustomerPlanReport.getAddVersion().longValue()).build();
            DeleteVersionResponse deleteVersionResponse = commerCustomerPlanReportService.deleteVersion(versionRequest);
            log.info("删除电商月度计划中间表数据，成功：{}， 入参：{}", JSONObject.toJSONString(deleteVersionResponse), deleteVersionResponse.getCount());
        }

        return null;
    }

    /**
     * 查询 es 中全部月度计划
     * @return
     */
    private List<OarsBoMonthlyPlanOfCommerceReport> getAllPlan() {
        List<OarsBoMonthlyPlanOfCommerceReport> list = new ArrayList<>();

        int start = 0;
        int limit = 500;
        GetListOarsBoMonthlyPlanOfCommerceReportRequest getListOarsBoMonthlyPlanOfCommerceReportRequest = new GetListOarsBoMonthlyPlanOfCommerceReportRequest();
        getListOarsBoMonthlyPlanOfCommerceReportRequest.setStart(start);
        getListOarsBoMonthlyPlanOfCommerceReportRequest.setLimit(limit);
        GetListOarsBoMonthlyPlanOfCommerceReportResponse listOarsBoMonthlyPlanOfCommerceReport = oarsBoMonthlyPlanOfCommerceReportService.getListOarsBoMonthlyPlanOfCommerceReport(getListOarsBoMonthlyPlanOfCommerceReportRequest);
        int allPage = listOarsBoMonthlyPlanOfCommerceReport.getTotal() / limit;
        if (listOarsBoMonthlyPlanOfCommerceReport.getTotal() % limit > 0) {
            allPage += 1;
        }
        if (ObjectUtils.isEmpty(listOarsBoMonthlyPlanOfCommerceReport)) {
            return list;
        }
        List<OarsBoMonthlyPlanOfCommerceReport> result = listOarsBoMonthlyPlanOfCommerceReport.getList();
        if (CollectionUtils.isEmpty(result)) {
            return list;
        }
        list.addAll(result);
        for (int i = 1; i < allPage; i++) {
            start = limit * i;
            getListOarsBoMonthlyPlanOfCommerceReportRequest.setStart(start);
            GetListOarsBoMonthlyPlanOfCommerceReportResponse plan = oarsBoMonthlyPlanOfCommerceReportService.getListOarsBoMonthlyPlanOfCommerceReport(getListOarsBoMonthlyPlanOfCommerceReportRequest);
            if (!ObjectUtils.isEmpty(plan) && !CollectionUtils.isEmpty(plan.getList())) {
                list.addAll(plan.getList());
            }
        }
        log.info("查询全量电商月度计划数据,数量：{}，详情：{}", list.size(), JSON.toJSONString(list));
        return list;
    }

    /**
     * 新增 月度计划数据
     * @param plan
     */
    public void addPlanCommerceReport(List<OarsBoMonthlyPlanOfCommerceReport> plan, Integer version) {
        log.info("新增月度计划：{}", JSONObject.toJSONString(plan));
        // 填充 货品名称 货品id：货品名称
        Set<String> ouiIdSet = plan.stream().map(OarsBoMonthlyPlanOfCommerceReport::getPlanOuterId).collect(Collectors.toSet());
        log.info("填充 货品名称 查询参数货品id：{}", JSONObject.toJSONString(ouiIdSet));
        Map<String, ScItemSDO> productCategorySDO = getProductCategorySDO(new ArrayList<>(ouiIdSet));
        log.info("填充 货品名称 结果：{}", JSONObject.toJSONString(productCategorySDO));

        // 平台code：平台id
        Set<String> platformCodes = plan.stream().map(OarsBoMonthlyPlanOfCommerceReport::getCustomerCommercePlatform).collect(Collectors.toSet());
        Map<String, String> platformIdByCode = platformNameById(new ArrayList<>(platformCodes));
        List<CommerCustomerPlanReport> commerCustomerPlanReports = coverCommerCustomerPlanReport(plan, version, productCategorySDO, platformIdByCode);
        log.info("填充 插入数据数据 结果：{}", JSONObject.toJSONString(commerCustomerPlanReports));
        batchAddPlan(commerCustomerPlanReports);
    }

    private void batchAddPlan(List<CommerCustomerPlanReport> commerCustomerPlanReports) {
        int sizeNum = commerCustomerPlanReports.size();
        if (sizeNum > 500) {
            for (int i = 0; i < sizeNum; i+=500) {
                List<CommerCustomerPlanReport> reportList = commerCustomerPlanReports.subList(i, (i + 500)>sizeNum?sizeNum:(i + 500));
                log.info("插入电商月度计划中间表数据，第"+i + "个，到"+(i+500)+"入参：{}", JSONObject.toJSONString(reportList));
                BatchAddRequest batchAddRequest = BatchAddRequest.builder().list(reportList).build();
                BatchAddResponse batchAddResponse = commerCustomerPlanReportService.batchAdd(batchAddRequest);
                log.info("插入电商月度计划中间表数据，第"+i + "个，到"+(i+500)+"结果：{}", JSONObject.toJSONString(batchAddResponse));
            }
        } else {
            log.info("插入电商月度计划中间表数据，入参：{}", JSONObject.toJSONString(commerCustomerPlanReports));
            BatchAddRequest batchAddRequest = BatchAddRequest.builder().list(commerCustomerPlanReports).build();
            BatchAddResponse batchAddResponse = commerCustomerPlanReportService.batchAdd(batchAddRequest);
            log.info("插入电商月度计划中间表数据，结果：{}", JSONObject.toJSONString(batchAddResponse));
        }

    }

    public List<CommerCustomerPlanReport> coverCommerCustomerPlanReport(List<OarsBoMonthlyPlanOfCommerceReport> plan, Integer version, Map<String, ScItemSDO> productCategorySDO, Map<String, String> platformIdByCode) {

        List<CommerCustomerPlanReport> list = new ArrayList<>();
        plan.forEach(monthPlan->{
            CommerCustomerPlanReport commerCustomerPlanReport = new CommerCustomerPlanReport();
            commerCustomerPlanReport.setPlanTime(monthPlan.getPlanPlanTime());
            String platformId = platformIdByCode.get(monthPlan.getCustomerCommercePlatform());
            commerCustomerPlanReport.setPlatformCode(StringUtils.isEmpty(platformId) ? OtsApplicationReportSdkConstants.OTHER_PLATFORM_ID() : platformId);
            commerCustomerPlanReport.setCustomerCode(monthPlan.getCustomerCustomerCode());
            commerCustomerPlanReport.setOuterId(monthPlan.getPlanOuterId());
            ScItemSDO scItemSDO = productCategorySDO.get(monthPlan.getPlanOuterId());
            if (!ObjectUtils.isEmpty(scItemSDO)) {
                commerCustomerPlanReport.setScItemName(scItemSDO.getTitle());
            }
            commerCustomerPlanReport.setOrgSaleDepartmentCode(monthPlan.getPlanOrgSaleChannelCode());
            commerCustomerPlanReport.setMonthFirstPlannedQuantity(monthPlan.getPlanMonthFirstPlannedQuantity());
            commerCustomerPlanReport.setMonthFirstReturnCount(monthPlan.getPlanMonthFirstReturnCount());
            commerCustomerPlanReport.setMonthFirstReviseConfirmCount(monthPlan.getPlanMonthFirstReviseConfirmCount());
            commerCustomerPlanReport.setMonthMiddlePlannedQuantity(monthPlan.getPlanMonthMiddlePlannedQuantity());
            commerCustomerPlanReport.setMonthMiddleReturnCount(monthPlan.getPlanMonthMiddleReturnCount());
            commerCustomerPlanReport.setMonthMiddleReviseConfirmCount(monthPlan.getPlanMonthMiddleReviseConfirmCount());
            commerCustomerPlanReport.setMonthLastPlannedQuantity(monthPlan.getPlanMonthLastPlannedQuantity());
            commerCustomerPlanReport.setMonthLastReturnCount(monthPlan.getPlanMonthLastReturnCount());
            commerCustomerPlanReport.setMonthLastReviseConfirmCount(monthPlan.getPlanMonthLastReviseConfirmCount());
            commerCustomerPlanReport.setAddVersion(version);
            list.add(commerCustomerPlanReport);
        });

        return list;
    }

    /**
     * 获取 平台code：平台id
     * @param platformCodes
     * @return
     */
    public Map<String, String> platformNameById(List<String> platformCodes) {
        // 分页查询 电商平台
        BaselineBatchQueryPlatforms2Request reportRequest = BaselineBatchQueryPlatforms2Request.builder()
                .platformCodes(platformCodes).build();
        log.info("查询电商平台入参："+JSONObject.toJSONString(reportRequest));
        Result<List<PlatformSDO>> listResult = baseDataService.baselineBatchQueryPlatforms2(reportRequest);
        log.info("查询电商平台结果："+JSONObject.toJSONString(reportRequest));

        if (ObjectUtils.isEmpty(listResult)) {
            return new HashMap<>();
        }
        List<PlatformSDO> result = listResult.getResult();
        if (CollectionUtils.isEmpty(result)) {
            return new HashMap<>();
        }

        Map<String, String> map = new HashMap<>();
        result.forEach(o->{
            map.put(o.getPlatformCode(), o.getPlatformId());
        });
        return map;
    }

    /**
     * 查询 货品对应的 类目 属性
     * @param outerIdList
     * @return
     */
    public Map<String, ScItemSDO> getProductCategorySDO(List<String> outerIdList) {

        // 查询 商品
        SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
        int pageNum = 1;
        int pageSize = 999;
        searchScItemRequest.setPageNum(pageNum);
        searchScItemRequest.setPageSize(pageSize);
        Map<String, Object> map = new HashMap<String, Object>(){{
            put("outerIdList", outerIdList);
            put("statusList", Arrays.asList(-1, 1));
        }};
        searchScItemRequest.setSearchReqDTO(map);
        Result<List<ScItemSDO>> listResult = baseDataService.searchScItem(searchScItemRequest);
        if (ObjectUtils.isEmpty(listResult)) {
            return null;
        }
        List<ScItemSDO> result = listResult.getResult();
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(result)) {
            return null;
        }
        do {
            pageNum+=1;
            Result<List<ScItemSDO>> listResult1 = baseDataService.searchScItem(searchScItemRequest);
            if (!ObjectUtils.isEmpty(listResult1) && !CollectionUtils.isEmpty(listResult1.getResult())) {
                result.addAll(listResult1.getResult());
            }
        } while (listResult.getTotal()>pageNum*pageSize);


        Map<String, List<ScItemSDO>> collect = result.stream().collect(Collectors.groupingBy(scItemSDO -> scItemSDO.getOuterId()));

        Map<String, ScItemSDO> mapScItem = new HashMap<>();
        collect.entrySet().forEach(entry->{
            mapScItem.put(entry.getKey(), entry.getValue().get(0));
        });
        return mapScItem;
    }

}
